package com.creatingrevolutions.vbukit.lib;

import com.creatingrevolutions.vbukit.lib.handler.BaseVbukitHandler;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.widget.ImageView;

public class AnimationController
{	
	Activity mContext;
	int[] mFrames;
	int mFps;
	ImageView mImageView;
	BaseVbukitHandler mHandler;
	int mIndex = 0;
	int mDelayMillis;
	Bitmap mBitmap = null;
	BitmapFactory.Options mBitmapOptions;
	boolean mIsRunning = false;
	boolean mIsShowing = false;
	boolean mLoopMode = false;
	
	public AnimationController(Activity context)
	{
		this.mContext = context;
	}
	
	public void animateFrames(boolean loopMode, ImageView imageView, int[] frames, int fps, 
			BaseVbukitHandler handler)
	{
		this.mLoopMode = loopMode;
		this.mFrames = frames;
		this.mFps = fps;
		this.mImageView = imageView;
		this.mHandler = handler;
		this.mDelayMillis = 1000 / fps;
		
		mBitmapOptions = new BitmapFactory.Options();
		mBitmapOptions.inBitmap = mBitmap;
		mBitmapOptions.inMutable = true;
		mBitmapOptions.inSampleSize = 1;
		
		doAnimation();
	}
	
	private void doAnimation()
	{
		mIsRunning = true;
		
		Thread t = new Thread(new Runnable()
		{
			@Override
			public void run()
			{
				while(mIsRunning)
				{
					if ( mIsShowing == false )
					{
						mIsShowing = true;
						
						mContext.runOnUiThread(new Runnable()
						{
							@Override
							public void run()
							{
								int imageRes = getNext();
								
								try {
									mBitmap = BitmapFactory.decodeResource(
											mImageView.getResources(), imageRes,
											mBitmapOptions);
								}
								catch (Exception e) {}
								
								if (mBitmap != null) {
									mImageView.setImageBitmap(mBitmap);
								}
								else {
									mImageView.setImageResource(imageRes);
									mBitmap.recycle();
									mBitmap = null;
								}
								
								mIsShowing = false;
							}
						});
						
						try {
							Thread.sleep(mDelayMillis);
						} 
						catch ( Exception e ) {}
						
					}
				}
				
				if ( mHandler != null ) {
					mHandler.updateInfo(true, null, null);
				}
			}
		});
		t.start();
	}
	
	private int getNext()
	{
		if ( mIndex + 1 < mFrames.length ) {
			mIndex ++;
		}
		else {
			if ( mLoopMode == false ) {
				stop();
			}
			mIndex = 0;
		}
		return mFrames[mIndex];
	}
	
	public void stop()
	{
		mIsRunning = false;
	}
	
}
